import { useQuery } from "@tanstack/react-query";
import {
	Button,
	Card,
	Col,
	Form,
	Input,
	InputNumber,
	Modal,
	Popconfirm,
	Radio,
	Row,
	Select,
	Space,
	message,
} from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import type { TableRowSelection } from "antd/es/table/interface";
import { useEffect, useState } from "react";

import orgService from "@/api/services/orgService";
import { IconButton, Iconify } from "@/components/icon";
import ProTag from "@/theme/antd/components/tag";
import {
	PlusOutlined,
	SearchOutlined,
	ReloadOutlined,
} from "@ant-design/icons";

import OrganizationChart from "./organization-chart";

import type { Organization } from "#/entity";

type SearchFormFieldType = Pick<Organization, "name" | "status">;

export default function OrganizationPage() {
	const [searchForm] = Form.useForm();
	const [organizationModalPros, setOrganizationModalProps] =
		useState<OrganizationModalProps>({
			formValue: {
				id: "",
				name: "",
				status: "enable",
			},
			title: "新增",
			show: false,
			onOk: () => {
				setOrganizationModalProps((prev) => ({ ...prev, show: false }));
				refetch();
			},
			onCancel: () => {
				setOrganizationModalProps((prev) => ({ ...prev, show: false }));
			},
		});

	const columns: ColumnsType<Organization> = [
		{ title: "组织名称", dataIndex: "name", width: 300 },
		{ title: "排序", dataIndex: "order", align: "center", width: 80 },
		{
			title: "状态",
			dataIndex: "status",
			align: "center",
			width: 100,
			render: (status) => (
				<ProTag color={status === "enable" ? "success" : "error"}>
					{status === "enable" ? "启用" : "禁用"}
				</ProTag>
			),
		},
		{ title: "描述", dataIndex: "desc", align: "center", width: 300 },
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 120,
			render: (_, record) => (
				<Space size="middle" className="flex justify-center">
					<Button
						type="link"
						icon={<Iconify icon="solar:pen-bold-duotone" size={18} />}
						onClick={() => onEdit(record)}
					>
						编辑
					</Button>
					<Popconfirm
						title="确定要删除该组织吗？"
						description="删除后不可恢复，请谨慎操作"
						okText="确定"
						cancelText="取消"
						placement="left"
						onConfirm={() => handleDelete(record.id)}
					>
						<Button
							type="link"
							danger
							icon={<Iconify icon="mingcute:delete-2-fill" size={18} />}
						>
							删除
						</Button>
					</Popconfirm>
				</Space>
			),
		},
	];

	const { data, refetch, isLoading } = useQuery({
		queryKey: ["orgs"],
		queryFn: orgService.getOrgList,
	});

	const handleDelete = async (id: string) => {
		try {
			await orgService.deleteOrg(id);
			message.success("删除成功");
			refetch();
		} catch (error) {
			message.error("删除失败");
		}
	};

	const onSearchFormReset = () => {
		searchForm.resetFields();
		refetch();
	};

	const onCreate = () => {
		setOrganizationModalProps((prev) => ({
			...prev,
			show: true,
			title: "新增组织",
			formValue: {
				...prev.formValue,
				id: "",
				name: "",
				order: 1,
				desc: "",
				status: "enable",
			},
		}));
	};

	const onEdit = (formValue: Organization) => {
		setOrganizationModalProps((prev) => ({
			...prev,
			show: true,
			title: "编辑组织",
			formValue,
		}));
	};

	return (
		<Space direction="vertical" size="large" className="w-full">
			<Card>
				<Form form={searchForm} onFinish={() => refetch()}>
					<Row gutter={[16, 16]}>
						<Col span={24} lg={6}>
							<Form.Item<SearchFormFieldType>
								label="组织名称"
								name="name"
								className="!mb-0"
							>
								<Input placeholder="请输入组织名称" allowClear />
							</Form.Item>
						</Col>
						<Col span={24} lg={6}>
							<Form.Item<SearchFormFieldType>
								label="状态"
								name="status"
								className="!mb-0"
							>
								<Select placeholder="请选择状态" allowClear>
									<Select.Option value="enable">
										<ProTag color="success">启用</ProTag>
									</Select.Option>
									<Select.Option value="disable">
										<ProTag color="error">禁用</ProTag>
									</Select.Option>
								</Select>
							</Form.Item>
						</Col>
						<Col span={24} lg={12}>
							<div className="flex justify-end">
								<Space>
									<Button icon={<ReloadOutlined />} onClick={onSearchFormReset}>
										重置
									</Button>
									<Button
										type="primary"
										htmlType="submit"
										icon={<SearchOutlined />}
									>
										查询
									</Button>
								</Space>
							</div>
						</Col>
					</Row>
				</Form>
			</Card>

			<Card
				title="组织列表"
				extra={
					<Button type="primary" icon={<PlusOutlined />} onClick={onCreate}>
						新增组织
					</Button>
				}
			>
				<Table
					rowKey="id"
					size="middle"
					loading={isLoading}
					scroll={{ x: "max-content" }}
					pagination={{
						showSizeChanger: true,
						showQuickJumper: true,
						showTotal: (total) => `共 ${total} 条记录`,
					}}
					columns={columns}
					dataSource={data}
				/>
			</Card>

			<Card title="组织图谱">
				<OrganizationChart organizations={data} />
			</Card>

			<OrganizationModal {...organizationModalPros} />
		</Space>
	);
}

type OrganizationModalProps = {
	formValue: Organization;
	title: string;
	show: boolean;
	onOk: VoidFunction;
	onCancel: VoidFunction;
};

function OrganizationModal({
	title,
	show,
	formValue,
	onOk,
	onCancel,
}: OrganizationModalProps) {
	const [form] = Form.useForm();
	useEffect(() => {
		form.setFieldsValue({ ...formValue });
	}, [formValue, form]);
	return (
		<Modal title={title} open={show} onOk={onOk} onCancel={onCancel}>
			<Form
				initialValues={formValue}
				form={form}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 18 }}
				layout="horizontal"
			>
				<Form.Item<Organization> label="组织名称" name="name" required>
					<Input />
				</Form.Item>
				<Form.Item<Organization> label="排序" name="order" required>
					<InputNumber style={{ width: "100%" }} />
				</Form.Item>
				<Form.Item<Organization> label="状态" name="status" required>
					<Radio.Group optionType="button" buttonStyle="solid">
						<Radio value="enable">启用</Radio>
						<Radio value="disable">禁用</Radio>
					</Radio.Group>
				</Form.Item>
				<Form.Item<Organization> label="描述" name="desc">
					<Input.TextArea />
				</Form.Item>
			</Form>
		</Modal>
	);
}
